package com.example.fresh_market.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.example.fresh_market.constants.StrConstant;
import com.example.fresh_market.databinding.ActivityLoginAdminBinding;
import com.example.fresh_market.request.ApiResponse;
import com.example.fresh_market.request.AuthRespVO;
import com.example.fresh_market.utils.HttpUtil;
import com.example.fresh_market.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class AdminLoginActivity extends AppCompatActivity {
    private ActivityLoginAdminBinding binding;
    private Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginAdminBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mContext = this;
        binding.buttonToUser.setOnClickListener(v -> {
            startActivity(new Intent(mContext, LoginActivity.class));
        });
        binding.adminLog.setOnClickListener(v -> {
            login();
        });
    }

    private void login() {
        String username = binding.adminUsername.getText().toString();
        String password = binding.adminPassword.getText().toString();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            Toast.makeText(mContext, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
        } else {
            Map<String, String> params = new HashMap<>();
            // 在这里添加表单字段
            params.put("username", username);
            params.put("password", password);
            params.put("loginType", "admin");
            HttpUtil.post(mContext, "/user/login", params, response -> {
                Log.d("", response);
                ToastUtil.showToast(mContext, "登录成功");
                Gson gson = new Gson();
                ApiResponse<AuthRespVO> apiResponse = gson.fromJson(response, new TypeToken<ApiResponse<AuthRespVO>>() {
                }.getType());
                if (apiResponse.getCode() == 200) {
                    SharedPreferences preferences = getSharedPreferences(StrConstant.CONFIG, MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString(StrConstant.TOKEN, apiResponse.getData().getToken());
                    editor.apply();
                    startActivity(new Intent(mContext, MainAdminActivity.class));
                }
            });
        }
    }
}
